//
//  SceneArmBaseViewController.m
//  wAudioShare
//
//  Created by Anson on 14-11-11.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "SceneArmBaseViewController.h"

@interface SceneArmBaseViewController () {
    
    
}

@property (strong, nonatomic) NSMutableArray *deletedDeviceList;//保存已经删除的设备，用于恢复在可选设备列表

@end

@implementation SceneArmBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initAll];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
- (void)reqConditionListWithCompleteBlock:(void (^)(id responseObject))completeBlock {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {
        
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Cond.cgi?action=do_list", ipUrl];
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            completeBlock(responseObject);
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

#pragma mark - 
- (void)setSelectDeviceList:(NSArray *)deviceList {
    self.canSelectDeviceList = [NSMutableArray arrayWithArray:deviceList];
}

- (void)initAll {
    
    _funcionOnOff = @[@"ON", @"OFF"];
    NSMutableArray *percent = [NSMutableArray arrayWithCapacity:100];
    for (NSInteger i=0; i<=100; i++) {
        [percent addObject:[NSString stringWithFormat:@"%ld%%", i]];
    }
    _dimmerLightPercent = percent;
    
    _thermostatAirMode = @[@"Heat", @"Cool", @"Auto", @"Resume"];
    
    NSMutableArray *list = [NSMutableArray arrayWithCapacity:50];
    for (NSInteger i=-50; i<120; i++) {
        [list addObject:[NSString stringWithFormat:@"%ld", i]];
    }
    _multiLevelSensorVal = list;
    
    self.attachDeviceModelList = [NSMutableArray arrayWithCapacity:10];
        
    _pickerView_DeviceList = [[UIPickerView alloc]initWithFrame:CGRectZero];
    _pickerView_DeviceList.dataSource = self;
    _pickerView_DeviceList.delegate = self;
    _pickerView_DeviceList.tag = PICKER_VIEW_DEVICE_LIST_TAG;
    _pickerView_DeviceList.showsSelectionIndicator = YES;
    
    _pickerView_Switch = [[UIPickerView alloc]initWithFrame:CGRectZero];
    _pickerView_Switch.dataSource = self;
    _pickerView_Switch.delegate = self;
    _pickerView_Switch.tag = PICKER_VIEW_FUNCTION_LIST_TAG;
    _pickerView_Switch.showsSelectionIndicator = YES;
    
    _pickerView_DimmerLight = [[UIPickerView alloc] initWithFrame:CGRectZero];
    _pickerView_DimmerLight.dataSource = self;
    _pickerView_DimmerLight.delegate = self;
    _pickerView_DimmerLight.tag = PICKER_VIEW_FUNCTION_LIST_TAG;
    _pickerView_DimmerLight.showsSelectionIndicator = YES;
    
    _pickerView_Temperature = [[UIPickerView alloc] initWithFrame:CGRectZero];
    _pickerView_Temperature.dataSource = self;
    _pickerView_Temperature.delegate = self;
    _pickerView_Temperature.tag = PICKER_VIEW_TEMPERATURE_LIST_TAG;
    _pickerView_Temperature.showsSelectionIndicator = YES;
    
    _pickerView_ThermostatMode = [[UIPickerView alloc] initWithFrame:CGRectZero];
    _pickerView_ThermostatMode.dataSource = self;
    _pickerView_ThermostatMode.delegate = self;
    _pickerView_ThermostatMode.tag = PICKER_VIEW_THERMOSTATMODE_TAG;
    _pickerView_ThermostatMode.showsSelectionIndicator = YES;

    
    if (self.btnSceneArmListSelect && self.btnSceneArmStateSelect){
    //只为Scene情景添加条件使用
        _pickerView_ArmConditionList = [[UIPickerView alloc] initWithFrame:CGRectZero];
        _pickerView_ArmConditionList.dataSource = self;
        _pickerView_ArmConditionList.delegate = self;
        _pickerView_ArmConditionList.tag = PICKER_VIEW_ARM_CONDITIONLIST_TAG;
        _pickerView_ArmConditionList.showsSelectionIndicator = YES;
        
        _pickerView_ArmStateList = [[UIPickerView alloc] initWithFrame:CGRectZero];
        _pickerView_ArmStateList.dataSource = self;
        _pickerView_ArmStateList.delegate = self;
        _pickerView_ArmStateList.tag = PICKER_VIEW_ARM_CONDITION_STATE_TAG;
        _pickerView_ArmStateList.showsSelectionIndicator = YES;
    }
    
}

- (void)reSetDevListSelect {
    _currentEditAttachedDevice = NO;
    _currentSelectDeviceType = -1;
    self.addDeviceFunctionModel = nil;
    self.selectedDeviceItemData = nil;
    [self.btnFunctionListSelect setTitle:@"" forState:UIControlStateNormal];
    [self.btnDeviceListSelect setTitle:@"" forState:UIControlStateNormal];
    
    [_pickerView_DeviceList reloadAllComponents];
}

- (void)resetSceneAddArmSelect {
    
    self.sceneAddArmConditionModel = nil;
    [self.btnSceneArmListSelect setTitle:@"" forState:UIControlStateNormal];
    [self.btnSceneArmStateSelect setTitle:@"" forState:UIControlStateNormal];
    
}

#pragma mark - UIButton
- (IBAction)deviceListSelectBtnClicked:(id)sender {
    [self doChoose:PICKER_VIEW_DEVICE_LIST_TAG];
}
//!** 情景下条件选择
- (IBAction)sceneArmListSelectedBtnClicked:(id)sender {
    [self doChoose:PICKER_VIEW_ARM_CONDITIONLIST_TAG];
}
//!*** 情景下条件激活选择
- (IBAction)sceneArmStateSelectedBtnClicked:(id)sender {
    [self doChoose:PICKER_VIEW_ARM_CONDITION_STATE_TAG];
}

- (IBAction)functionSelectedBtnClicked:(id)sender {
    [self doChoose:PICKER_VIEW_FUNCTION_LIST_TAG];
}

- (IBAction)editAttachDeviceListBtnClicked:(id)sender {
    [self.attachDeviceListView setEditing:!self.attachDeviceListView.editing animated:YES];
}

- (IBAction)backToPreViewControllerBtnClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIPickerView 
-(void)doChoose:(NSInteger)tag
{
    UIPickerView *picker = nil;
    int index = 0;
    if (tag == PICKER_VIEW_DEVICE_LIST_TAG)
    {
        picker = _pickerView_DeviceList;
        
    }
    else if (tag == PICKER_VIEW_FUNCTION_LIST_TAG)
    {
        switch (_currentSelectDeviceType) {
            case SceneDeviceTypeBinarySensor:
            case SceneDeviceTypeMultilevelSensor:
            case SceneDeviceTypeSwitch:
            case SceneDeviceTypeMotor:
            case SceneDeviceTypePowerMeter:
            case SceneDeviceTypeThermostat:
            case SceneDeviceTypeDoorLock:
                picker = _pickerView_Switch;
                break;
                
            case SceneDeviceTypeDimmer:
                picker = _pickerView_DimmerLight;
                break;
                
            default:
                break;
        }
    }else if (tag == PICKER_VIEW_THERMOSTATMODE_TAG) {
        
        picker = _pickerView_ThermostatMode;
    }else if (tag == PICKER_VIEW_TEMPERATURE_LIST_TAG) {
        picker = _pickerView_Temperature;
    }else if (tag == PICKER_VIEW_ARM_CONDITIONLIST_TAG) {
        picker = _pickerView_ArmConditionList;
    }else if (tag == PICKER_VIEW_ARM_CONDITION_STATE_TAG) {
        if (self.sceneAddArmConditionModel) {
            picker = _pickerView_ArmStateList;
        }        
    }
    
    if (!picker) return;
    
    [picker selectRow:index inComponent:0 animated:NO];
    
    //ios 7 的自定义UIActionSheet
    if ([[UIDevice currentDevice].systemVersion floatValue] < 8)
    {
        self.actionPicker = [[ActionPicker alloc]initWithTitle:@"" delegate:self picker:picker];
        self.actionPicker.tag = tag;
        [self.actionPicker showInView:self.view.superview];
    }
    else
    {
        [self alertWithPicer:picker];
    }
}

- (void)pickerViewConfirmForDevList:(NSInteger)picker_selected_index {
    NSDictionary *devData = [self.canSelectDeviceList objectAtIndex:picker_selected_index];
    NSString *title = devData[@"Alias"];
    
    //NSString *dt = devData[@"DeviceType"]; NSLog(@"%ld", [dt integerValue]);
    _currentSelectDeviceType = [devData[@"DeviceType"] integerValue];
    self.selectedDeviceItemData = devData;
    
    [self.btnDeviceListSelect setTitle:title forState:UIControlStateNormal];
    
    self.addDeviceFunctionModel = [[SceneDeviceModel alloc] init];
    self.addDeviceFunctionModel.deviceType = _currentSelectDeviceType;
    self.addDeviceFunctionModel.title = title;
    self.addDeviceFunctionModel.deviceId = devData[@"ZID"];
    [self.btnFunctionListSelect setTitle:@"" forState:UIControlStateNormal];
    
}

- (void)pickerViewConfirmForFunctionList:(NSInteger)picker_selected_index {
    switch (_currentSelectDeviceType) {
        case SceneDeviceTypeBinarySensor:
        case SceneDeviceTypeMultilevelSensor:
        case SceneDeviceTypeSwitch:
        case SceneDeviceTypeMotor:
        case SceneDeviceTypePowerMeter:
        case SceneDeviceTypeDoorLock:
        {
            self.addDeviceFunctionModel.isOn = (picker_selected_index == 0);
            [self.btnFunctionListSelect setTitle:(self.addDeviceFunctionModel.isOn ? @"ON":@"OFF") forState:UIControlStateNormal];
            break;
        }
            
        case SceneDeviceTypeDimmer:
        {
            self.addDeviceFunctionModel.percent = picker_selected_index;
            [self.btnFunctionListSelect setTitle:[NSString stringWithFormat:@"%ld%%", self.addDeviceFunctionModel.percent] forState:UIControlStateNormal];
            break;
        }
            
        case SceneDeviceTypeThermostat:
        {
            self.addDeviceFunctionModel.isOn = (picker_selected_index == 0);
            if (self.addDeviceFunctionModel.isOn ) {
                [self doChoose:PICKER_VIEW_THERMOSTATMODE_TAG];
            }
            
            [self.btnFunctionListSelect setTitle:(self.addDeviceFunctionModel.isOn ? @"ON":@"OFF") forState:UIControlStateNormal];
            break;
        }
        default:
            break;
    }
}

- (void)pickerViewConfirmForThermostatmode:(NSInteger)picker_selected_index {
    self.addDeviceFunctionModel.mode = _thermostatAirMode[picker_selected_index];
    if ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"] || [self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"cool"]) {
        [self doChoose:PICKER_VIEW_TEMPERATURE_LIST_TAG];
    }
}

- (void)pickerViewConfirmForTemperature:(NSInteger)picker_selected_index {
    self.addDeviceFunctionModel.thermostatTemperature = [_temperatureArray[picker_selected_index] integerValue];
}

- (void)pickerViewConfirmForSceneArmList:(NSInteger)picker_selected_index {
    [self resetSceneAddArmSelect];
    ArmModel *arm = _armConditionList[picker_selected_index];
    self.sceneAddArmConditionModel = [arm copy];
    [self.btnSceneArmListSelect setTitle:arm.label forState:UIControlStateNormal];
}

- (void)pickerViewConfirmForSceneArmState:(NSInteger)picker_selected_index {
    
    self.sceneAddArmConditionModel.active = (picker_selected_index == 0);
    [self.btnSceneArmStateSelect setTitle:(self.sceneAddArmConditionModel.active? @"ON":@"OFF") forState:UIControlStateNormal];
}

-(void)didOKButtonPressed:(ActionPicker *)picker
{
    if (picker.tag == PICKER_VIEW_DEVICE_LIST_TAG)
    {
        NSInteger picker_selected_index= [_pickerView_DeviceList selectedRowInComponent:0];
        [self pickerViewConfirmForDevList:picker_selected_index];
        
        [self resetSceneAddArmSelect];
        
    }
    else if(picker.tag == PICKER_VIEW_FUNCTION_LIST_TAG)
    {
        switch (_currentSelectDeviceType) {
            case SceneDeviceTypeBinarySensor:
            case SceneDeviceTypeMultilevelSensor:
            case SceneDeviceTypeSwitch:
            case SceneDeviceTypeMotor:
            case SceneDeviceTypePowerMeter:
            case SceneDeviceTypeDoorLock:
            {
                NSInteger picker_selected_index= [_pickerView_Switch selectedRowInComponent:0];
                [self pickerViewConfirmForFunctionList:picker_selected_index];
                break;
            }
                
            case SceneDeviceTypeDimmer:
            {
                NSInteger picker_selected_index= [_pickerView_DimmerLight selectedRowInComponent:0];
                [self pickerViewConfirmForFunctionList:picker_selected_index];
                break;
            }
                
            case SceneDeviceTypeThermostat:
            {
                NSInteger picker_selected_index= [_pickerView_Switch selectedRowInComponent:0];
                [self pickerViewConfirmForFunctionList:picker_selected_index];
                break;
            }
                
            default:
                break;
        }
    }
    else if(picker.tag == PICKER_VIEW_THERMOSTATMODE_TAG)
    {
        NSInteger picker_selected_index= [_pickerView_ThermostatMode selectedRowInComponent:0];
        [self pickerViewConfirmForThermostatmode:picker_selected_index];
    }
    else if(picker.tag == PICKER_VIEW_TEMPERATURE_LIST_TAG)
    {
        NSInteger picker_selected_index= [_pickerView_Temperature selectedRowInComponent:0];
        [self pickerViewConfirmForTemperature:picker_selected_index];
        
    }else if(picker.tag == PICKER_VIEW_ARM_CONDITIONLIST_TAG) {
       
        [self reSetDevListSelect];
        [self pickerViewConfirmForSceneArmList:[_pickerView_ArmConditionList selectedRowInComponent:0]];
        
    }else if(picker.tag == PICKER_VIEW_ARM_CONDITION_STATE_TAG) {
      
        [self pickerViewConfirmForSceneArmState:[_pickerView_ArmStateList selectedRowInComponent:0]];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView1 numberOfRowsInComponent:(NSInteger)component;
{
    if (pickerView1.tag == PICKER_VIEW_DEVICE_LIST_TAG)
    {
        return self.canSelectDeviceList.count;
    }
    else if(pickerView1.tag == PICKER_VIEW_FUNCTION_LIST_TAG)
    {
        switch (_currentSelectDeviceType) {
            case SceneDeviceTypeBinarySensor:
            case SceneDeviceTypeMultilevelSensor:
            case SceneDeviceTypeSwitch:
            case SceneDeviceTypeMotor:
            case SceneDeviceTypePowerMeter:
            case SceneDeviceTypeThermostat:
            case SceneDeviceTypeDoorLock:
                return _funcionOnOff.count;
                break;
                
            case SceneDeviceTypeDimmer:
                return _dimmerLightPercent.count;
                break;
                
            default:
                break;
        }
        return 0;
    }
    else if(pickerView1.tag == PICKER_VIEW_TEMPERATURE_LIST_TAG)
    {
        if (!_temperatureArray) {
            _temperatureArray = [[NSArray alloc] initWithObjects:@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30",nil];
        }
        return [_temperatureArray count];
    }
    else if(pickerView1.tag == PICKER_VIEW_THERMOSTATMODE_TAG)
    {
        return _thermostatAirMode.count;
    }else if(pickerView1.tag == PICKER_VIEW_ARM_CONDITIONLIST_TAG) {
        return _armConditionList.count;
    }else if(pickerView1.tag == PICKER_VIEW_ARM_CONDITION_STATE_TAG) {
        return _funcionOnOff.count;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView1 titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView1.tag == PICKER_VIEW_DEVICE_LIST_TAG)
    {
        NSDictionary *devData = [self.canSelectDeviceList objectAtIndex:row];
        return [devData objectForKey:@"Alias"];
        
    }
    else if(pickerView1.tag == PICKER_VIEW_FUNCTION_LIST_TAG)
    {
        switch (_currentSelectDeviceType) {
            case SceneDeviceTypeBinarySensor:
            case SceneDeviceTypeMultilevelSensor:
            case SceneDeviceTypeSwitch:
            case SceneDeviceTypeMotor:
            case SceneDeviceTypePowerMeter:
            case SceneDeviceTypeThermostat:
            case SceneDeviceTypeDoorLock:
            {
                return [_funcionOnOff objectAtIndex:row];
                break;
            }
                
            case SceneDeviceTypeDimmer:
            {
                return [_dimmerLightPercent objectAtIndex:row];
                break;
            }
                
            default:
                break;
        }
        
    }
    else if(pickerView1.tag == PICKER_VIEW_TEMPERATURE_LIST_TAG)
    {
        return [_temperatureArray objectAtIndex:row];
    }
    else if (pickerView1.tag == PICKER_VIEW_THERMOSTATMODE_TAG)
    {
        return _thermostatAirMode[row];
    }else if(pickerView1.tag == PICKER_VIEW_ARM_CONDITIONLIST_TAG) {
         ArmModel *armModelData = _armConditionList[row];
        return armModelData.label;
        
    }else if(pickerView1.tag == PICKER_VIEW_ARM_CONDITION_STATE_TAG) {
        return _funcionOnOff[row];
    }
    return @"";
}

#pragma mark - ios UIAlertController
- (void)alertWithPicer:(UIPickerView *)picker
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:@"\n\n\n\n\n\n\n\n\n\n\n"// change UIAlertController height
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    //Make a frame for the picker & then create the picker
    CGRect pickerFrame = CGRectMake(12, 12, 270, 250);
    picker.frame = pickerFrame;
    ios8Picker = picker;
    NSLog(@"%ld",(long)ios8Picker.tag);
    
    
    //set the pickers selection indicator to true so that the user will now which one that they are chosing
    [picker setShowsSelectionIndicator:YES];
    
    //Add the picker to the alert controller
    [alert.view addSubview:picker];
    
    //make the toolbar view
    UIToolbar *toolView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, alert.view.frame.size.width-16, kToolBarHeight)];
    toolView.backgroundColor = [UIColor blackColor]; //set it's background
    toolView.barStyle = UIBarStyleBlackTranslucent;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, kToolBarHeight)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    //    titleLabel.text = title;
    UIBarButtonItem *bbtTitle = [[UIBarButtonItem alloc] initWithCustomView:titleLabel];
    UIBarButtonItem *bbtSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *bbtOK = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(OKWithPicker)];
    bbtOK.width = 60.f;
    UIBarButtonItem *bbtCancel = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(CancleWithPicker)];
    bbtCancel.width = 60.f;
    toolView.items = [NSArray arrayWithObjects:bbtCancel,bbtSpace,bbtTitle,bbtSpace,bbtOK, nil];
    
    [alert.view addSubview:toolView];
    
    [self presentViewController:alert animated:NO completion:nil];
}

- (void)OKWithPicker
{
    NSInteger picker_selected_index = -1;
    if (ios8Picker.tag == PICKER_VIEW_DEVICE_LIST_TAG)
    {
        picker_selected_index= [_pickerView_DeviceList selectedRowInComponent:0];
        [self pickerViewConfirmForDevList:picker_selected_index];
    }
    else if(ios8Picker.tag == PICKER_VIEW_FUNCTION_LIST_TAG)
    {
        switch (_currentSelectDeviceType) {
            case SceneDeviceTypeBinarySensor:
            case SceneDeviceTypeMultilevelSensor:
            case SceneDeviceTypeSwitch:
            case SceneDeviceTypeMotor:
            case SceneDeviceTypePowerMeter:
            case SceneDeviceTypeDoorLock:
            {
                picker_selected_index= [_pickerView_Switch selectedRowInComponent:0];
                [self pickerViewConfirmForFunctionList:picker_selected_index];
                break;
            }
                
            case SceneDeviceTypeDimmer:
            {
                picker_selected_index= [_pickerView_DimmerLight selectedRowInComponent:0];
                [self pickerViewConfirmForFunctionList:picker_selected_index];
                break;
            }
                
            case SceneDeviceTypeThermostat:
            {
                picker_selected_index= [_pickerView_Switch selectedRowInComponent:0];
                [self pickerViewConfirmForFunctionList:picker_selected_index];
                break;
            }
                
            default:
                break;
        }
        
    }
    else if(ios8Picker.tag == PICKER_VIEW_TEMPERATURE_LIST_TAG)
    {
        picker_selected_index = [_pickerView_Temperature selectedRowInComponent:0];
        [self pickerViewConfirmForTemperature:picker_selected_index];
    }
    else if(ios8Picker.tag == PICKER_VIEW_THERMOSTATMODE_TAG)
    {
        picker_selected_index = [_pickerView_ThermostatMode selectedRowInComponent:0];
        [self pickerViewConfirmForThermostatmode:picker_selected_index];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)CancleWithPicker
{
     [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.attachDeviceModelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"SceneDeviceCell";
    SceneDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell =  [[[NSBundle mainBundle] loadNibNamed:cellId owner:self options:nil] lastObject];
    }
    
    cell.sceneData = [self.attachDeviceModelList objectAtIndex:indexPath.row];
    
    [cell.switchBtn addTarget:self action:@selector(resetSceneDeviceCell:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    id data = self.attachDeviceModelList[indexPath.row];
    [self deleteAttachDevice:data];    
}

#pragma mark -
- (void)resetSceneDeviceCell:(UIButton *)sender {
    
    CGRect btnRect = sender.frame;
    CGPoint p = [sender convertPoint:btnRect.origin toView:self.attachDeviceListView];
    NSIndexPath *indexPath = [self.attachDeviceListView indexPathForRowAtPoint:CGPointMake(0, p.y)];
    //DLog(@"%ld", indexPath.row);
    if (indexPath.row < self.attachDeviceModelList.count) {
        
        [self reSetDevListSelect];
        _currentEditAttachedDevice = YES;
        
        id data = self.attachDeviceModelList[indexPath.row];
        if ([data isMemberOfClass:SceneDeviceModel.class]) {
            
            SceneDeviceModel *sceneData = self.attachDeviceModelList[indexPath.row];
            self.addDeviceFunctionModel = [sceneData copy];
            _currentSelectDeviceType = sceneData.deviceType;
            
            [self doChoose:PICKER_VIEW_FUNCTION_LIST_TAG];
            
        }else if ( [data isMemberOfClass:ArmModel.class]) {
            
            ArmModel *armModelData = data;
            self.sceneAddArmConditionModel = [armModelData copy];
            [self doChoose:PICKER_VIEW_ARM_CONDITION_STATE_TAG];
        }
    }
}

//!由于空调设置开状态后，还需要再发一请求设置模式和值，所以需要有个UrlBase
- (void)sendReqAddNewDeviceToSceneWithURL:(NSString *)urlStr thermostateBaseUrl:(NSString *)urlBase {
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            if (self.addDeviceFunctionModel.deviceType == SceneDeviceTypeThermostat
                && self.addDeviceFunctionModel.isOn
                && ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"] || [self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"cool"] )) {
                //发送设置空调温度请求
                NSString * urlThermostat = [urlBase stringByAppendingFormat:@"&cmd=0x43&index=%d&value=%ld", ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"]?1:2), self.addDeviceFunctionModel.thermostatTemperature];
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    [Utitlity commonHTTPMethod:urlThermostat responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        if (!responseObject) return;
                        NSDictionary *retJsonData = responseObject;
                        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                            
                            [self.canSelectDeviceList removeObject:self.selectedDeviceItemData];
                            [self.attachDeviceModelList addObject:self.addDeviceFunctionModel];
                            [self reSetDevListSelect];
                            [self.attachDeviceListView reloadData];
                        }
                        
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        [activity stopAnimating];
                        NSLog(@"error:%@",error);
                        
                    }];
                });
                
            }else {
                
                [self.canSelectDeviceList removeObject:self.selectedDeviceItemData];
                [self.attachDeviceModelList addObject:self.addDeviceFunctionModel];
                [self reSetDevListSelect];
                [self.attachDeviceListView reloadData];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
        
    }];
    
}

- (void)sendReqConfigAttachDeviceWithURL:(NSString *)urlStr thermostateBaseUrl:(NSString *)urlBase {
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            if (self.addDeviceFunctionModel.deviceType == SceneDeviceTypeThermostat
                && self.addDeviceFunctionModel.isOn
                && ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"] || [self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"cool"] )) {
                //发送设置空调温度请求
                NSString * urlThermostat = [urlBase stringByAppendingFormat:@"&cmd=0x43&index=%d&value=%ld", ([self.addDeviceFunctionModel.mode.lowercaseString isEqualToString:@"heat"]), self.addDeviceFunctionModel.thermostatTemperature];
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    [Utitlity commonHTTPMethod:urlThermostat responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        if (!responseObject) return;
                        NSDictionary *retJsonData = responseObject;
                        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                            
                            [self replaceDeviceModelListWithData:self.addDeviceFunctionModel];
                            [self.attachDeviceListView reloadData];
                            [self reSetDevListSelect];
                        }
                        
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        [activity stopAnimating];
                        NSLog(@"error:%@",error);
                        
                    }];
                });
                
            }else {
                
                [self replaceDeviceModelListWithData:self.addDeviceFunctionModel];
                [self.attachDeviceListView reloadData];
                [self reSetDevListSelect];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
        
    }];
    
}

- (void)replaceDeviceModelListWithData:(SceneDeviceModel *)data {
    
    for (NSInteger i=0; i<self.attachDeviceModelList.count; i++) {
        
        SceneDeviceModel *item = self.attachDeviceModelList[i];
        if ([item.deviceId isEqualToString:data.deviceId]) {
            
            [self.attachDeviceModelList replaceObjectAtIndex:i withObject:data];
            break;
        }
    }
}

- (void)replaceSceneArmModelListWithData:(ArmModel *)replaceData {
    
    for (NSInteger i=0; i<self.attachDeviceModelList.count; i++) {
        
        id item = self.attachDeviceModelList[i];
        if ( [item isMemberOfClass:ArmModel.class]) {
            
            ArmModel *armModelData = (ArmModel *)item;
            if (replaceData && armModelData.armId == replaceData.armId)
                [self.attachDeviceModelList replaceObjectAtIndex:i withObject:replaceData];
            break;
        }
    }
}

-(void)deleteAttachDevice:(id)modelData {
    
}

@end
